import { create } from "zustand";
import type { StateCreator } from "zustand";
import { immer } from "zustand/middleware/immer";
import {
  devtools,
  persist,
  subscribeWithSelector,
  createJSONStorage,
} from "zustand/middleware";
import { createSelectors } from "@/utils/createSelectors";
import dayjs from "dayjs";

/** ---------------state start--------------- */
const initState = {
  collectSourceList: [] as any[], // 任务列表
  collectTargetList: [] as any[], // 目标列表
  isInput: false, // 是否采集
  isStart: false, // 是否开始
  log: "", // 日志
};
/** ---------------state end--------------- */

/** ---------------方法start--------------- */

export const setLog = (text: string) => {
  const currentTime = dayjs().format("YYYY-MM-DD HH:mm:ss");
  text = `[${currentTime}]：${text}\n`;
  useCollectStore.setState((state) => {
    state.log += text;
  });
};

/** ---------------方法end--------------- */

const createCollectSlice: StateCreator<
  typeof initState,
  [
    ["zustand/immer", never],
    ["zustand/devtools", unknown],
    ["zustand/subscribeWithSelector", never],
    ["zustand/persist", unknown]
  ]
> = () => initState;

export const useCollectStore = createSelectors(
  create<typeof initState>()(
    immer(
      devtools(
        subscribeWithSelector(
          persist(createCollectSlice, {
            // 存储名称(必须唯一)
            name: "collectStore",
            // 自定义存储(默认localStorage)
            storage: createJSONStorage(() => sessionStorage),
            // 只存储某个字段
            // partialize: (state) => ({ bears: state.bears, color: state.color }),
            // 不存储某个字段
            // partialize: (state) =>
            //   Object.fromEntries(
            //     Object.entries(state).filter(
            //       ([key]) =>
            //         !["currentHwnd"].includes(
            //           key
            //         )
            //     )
            //   ),
          })
        ),
        {
          enabled: true, // 是否启用devtools
          name: "collectStore", // devtools名称
        }
      )
    )
  )
);
